package org.hejw.rpc.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.hejw.rpc.info.ServiceInfo;

/**
 * 涉及到服务器之间通信，毫无疑问，直接上netty；
 */
public class NettyClient implements NetClient{


    public byte[] sendRequest(byte[] data, ServiceInfo sinfo) throws Throwable {
        String[] addInfoArray = sinfo.getAddress().split(":");
        final NettySendHandler sendHandler = new NettySendHandler(data);

        byte[] respData = null;
        // 配置客户端
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(sendHandler);
                    }
                });
            // 启动客户端连接
            b.connect(addInfoArray[0], Integer.valueOf(addInfoArray[1])).sync();
            respData = (byte[]) sendHandler.rspData();
        } finally {
            group.shutdownGracefully();
        }
        return respData;
    }
}
